package com.glsc.ngateway.opmanage.service.ledger;

import com.glsc.ngateway.common.api.common.utils.DateUtil;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.ledger.*;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.task.TaskInfo;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.ledger.*;
import com.glsc.ngateway.opmanage.dto.BusinessLedgerFileExcelDto;
import com.glsc.ngateway.opmanage.enums.TaskTypeUrlEnum;
import com.glsc.ngateway.opmanage.exception.PlatformException;
import com.glsc.ngateway.opmanage.service.MailService;
import com.glsc.ngateway.opmanage.service.other.TradingDayService;
import com.glsc.ngateway.opmanage.service.task.TaskInfoService;
import com.glsc.ngateway.opmanage.utils.DateUtils;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import com.glsc.ngateway.opmanage.utils.report.ReportFileConfigEnum;
import com.glsc.ngateway.opmanage.utils.report.ReportFileUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;

import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.glsc.ngateway.opmanage.utils.DateUtils.formatDate;

@Service
@Slf4j
public class LedgerService {

    @Resource
    private LedgerTemplateRepository ledgerTemplateRepository;

    @Resource
    private LedgerTaskTemplateRepository ledgerTaskTemplateRepository;

    @Resource
    private BusinessLedgerRepository businessLedgerRepository;

    @Resource
    private BusinessLedgerTaskRepository businessLedgerTaskRepository;

    @Resource
    private TaskInfoService taskInfoService;

    @Resource
    private LedgerTaskFileTemplateRepository ledgerTaskFileTemplateRepository;

    @Resource
    private BusinessLedgerTaskFileRepository businessLedgerTaskFileRepository;

    @Resource
    private BusinessLedgerOptLogRepository businessLedgerOptLogRepository;

    @Resource
    private MailService mailService;

    @Resource
    private TradingDayService tradingDayService;



    /**
     * 分页查询台账模板信息
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<LedgerTemplate> findLedgerTemplatePage(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<LedgerTemplate> page = ledgerTemplateRepository.findAll(SpecificationUtil.buildSpecification(param, LedgerTemplate.class), pageable);

        return page;
    }

    /**
     * 根据 ledgerTemplateId 查找任务模板信息
     *
     * @param ledgerTemplateId
     * @return
     */
    public List<LedgerTaskTemplate> listTemplateByLedgerTemplateId(Integer ledgerTemplateId) {
        return ledgerTaskTemplateRepository.findAll(Example.of(LedgerTaskTemplate.builder().ledgerTemplateId(ledgerTemplateId).build()));
    }

    /**
     * 保存模板信息
     *
     * @param template
     */
    public void saveLedgerTemplate(LedgerTemplate template) {
        Assert.isTrue(StringUtils.isNotBlank(template.getToTaskType()), "[待办任务类型]不可为空");
        //模板的名称不可重复
        List<LedgerTemplate> nameList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().name(template.getName()).build()));
        Assert.isTrue((CollectionUtils.isEmpty(nameList) ||
                (Objects.nonNull(template.getId()) && nameList.size() == 1 && nameList.get(0).getId() == template.getId())), "名称为[" + template.getName() + "]的台账模板已经存在，请修改台账模板名称");

        LedgerTemplate newLedgerTemplate = ledgerTemplateRepository.save(template);
        List<LedgerTaskTemplate> oldLedgerTaskTemplates = listTemplateByLedgerTemplateId(newLedgerTemplate.getId());
        List<LedgerTaskTemplate> taskTemplateList = template.getTaskTemplateList();
        checkTaskTemplate(taskTemplateList);
        if (CollectionUtils.isEmpty(taskTemplateList)) {
            ledgerTaskTemplateRepository.deleteAllById(taskTemplateList.stream().map(LedgerTaskTemplate::getId).collect(Collectors.toList()));
            return;
        }
        List<Integer> taskIdList = Lists.newArrayList();
        for (LedgerTaskTemplate ledgerTaskTemplate : taskTemplateList) {
            ledgerTaskTemplate.setLedgerTemplateId(newLedgerTemplate.getId());
            if (Objects.nonNull(ledgerTaskTemplate.getLedgerTemplateId())) {
                taskIdList.add(ledgerTaskTemplate.getId());
            }
        }

        if (CollectionUtils.isEmpty(oldLedgerTaskTemplates)) {
            ledgerTaskTemplateRepository.saveAll(taskTemplateList);
        } else {
            List<LedgerTaskTemplate> removeList = oldLedgerTaskTemplates.stream().filter(e -> !taskIdList.contains(e.getId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(removeList)) {
                ledgerTaskTemplateRepository.deleteAllById(removeList.stream().map(LedgerTaskTemplate::getId).collect(Collectors.toList()));
            }
            ledgerTaskTemplateRepository.saveAll(taskTemplateList);
        }
    }

    public void checkTaskTemplate(List<LedgerTaskTemplate> taskTemplateList) {
        if (CollectionUtils.isNotEmpty(taskTemplateList)) {
            for (LedgerTaskTemplate ledgerTaskTemplate : taskTemplateList) {
                Assert.isTrue(StringUtils.isNotBlank(ledgerTaskTemplate.getWorkType()), "任务列表中的[工作类型]不可为空");
                Assert.isTrue(StringUtils.isNotBlank(ledgerTaskTemplate.getWorkItem()), "任务列表中的[工作事项]不可为空");
                Assert.isTrue(StringUtils.isNotBlank(ledgerTaskTemplate.getWorkItemType()), "任务列表中的[工作事项类型]不可为空");
                Assert.isTrue(StringUtils.isNotBlank(ledgerTaskTemplate.getWorkValueType()), "任务列表中的[工作值类型]不可为空");
                Assert.isTrue(StringUtils.isNotBlank(ledgerTaskTemplate.getWorkValueRequire()), "任务列表中的[任务是否必需完成]不可为空");
                Assert.isTrue(Objects.nonNull(ledgerTaskTemplate.getTaskSort()), "任务列表中的[任务排序]不可为空");
            }
        }
    }

    /**
     * 根据id查找台账模板和任务模板信息
     *
     * @param id
     * @return
     */
    public LedgerTemplate findLedgerTemplateById(Integer id) {
        Optional<LedgerTemplate> optional = ledgerTemplateRepository.findById(id);
        if (optional.isPresent()) {
            LedgerTemplate ledgerTemplate = optional.get();
            List<LedgerTaskTemplate> taskList = ledgerTaskTemplateRepository.findAll(Example.of(LedgerTaskTemplate.builder().ledgerTemplateId(id).build()));
            if (CollectionUtils.isNotEmpty(taskList)) {
                ledgerTemplate.setTaskTemplateList(taskList.stream().sorted(Comparator.comparing(LedgerTaskTemplate::getTaskSort)).collect(Collectors.toList()));
            }
            return ledgerTemplate;
        }
        return null;
    }

    /**
     * 根据id删除模板和任务模板信息
     *
     * @param templateId
     */
    public void deleteTempLateById(Integer templateId) {
        ledgerTemplateRepository.deleteById(templateId);
        List<LedgerTaskTemplate> ledgerTaskTemplates = listTemplateByLedgerTemplateId(templateId);
        if (CollectionUtils.isNotEmpty(ledgerTaskTemplates)) {
            ledgerTaskTemplateRepository.deleteAllById(ledgerTaskTemplates.stream().map(LedgerTaskTemplate::getId).collect(Collectors.toList()));
        }
    }

    /**
     * 查找所有台账模板信息
     *
     * @return
     */
    public List<LedgerTemplate> listAllTemplate() {
        return ledgerTemplateRepository.findAll();
    }

    /**
     * 分页查询台账信息
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<BusinessLedger> findLedgerPage(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<BusinessLedger> page = businessLedgerRepository.findAll(SpecificationUtil.buildSpecification(param, BusinessLedger.class), pageable);

        return page;
    }


    /**
     * 根据完成人id查询今日此人完成的台账任务列表
     *
     * @param finishId
     * @return
     */
    public List<BusinessLedger> findTodayFinishLedgerByFinishId(Long finishId) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        List<BusinessLedger> ledgerList = businessLedgerRepository.findAll(Example.of(BusinessLedger.builder().finishTime(DateUtil.getNowDateString()).finishId(finishId).build()));

        return ledgerList;
    }

    /**
     * 分页查询台账资料信息
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<BusinessLedgerTaskFile> findLedgerFilePage(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "businessLedgerTaskId";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);

        Page<BusinessLedgerTaskFile> page = businessLedgerTaskFileRepository.findAll(SpecificationUtil.buildSpecification(param, BusinessLedgerTaskFile.class), pageable);
        return page;
    }


    public Page<BusinessLedgerTaskFile> findLedgerFilePageBySpec(int pageNo, int pageSize, Specification spec) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "businessLedgerTaskId";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);

        Page<BusinessLedgerTaskFile> page = businessLedgerTaskFileRepository.findAll(spec, pageable);
        return page;
    }

    public List<BusinessLedgerTaskFile> findLedgerFileBySpec(Specification spec) {
        return businessLedgerTaskFileRepository.findAll(spec);
    }

    /**
     * 根据台账id查找台账任务信息
     *
     * @param ledgerId
     * @return
     */
    public List<BusinessLedgerTask> listLedgerByLedgerId(Integer ledgerId) {
        return businessLedgerTaskRepository.findAll(Example.of(BusinessLedgerTask.builder().ledgerId(ledgerId).build()));
    }

    public List<BusinessLedgerTask> listLedgerById(List<Integer> id) {
        return businessLedgerTaskRepository.listLedgerById(id);
    }

    /**
     * 根据id查找台账和任务模板信息
     *
     * @param id
     * @return
     */
    public BusinessLedger findLedgerById(Integer id) {
        Optional<BusinessLedger> optional = businessLedgerRepository.findById(id);
        if (optional.isPresent()) {
            BusinessLedger ledger = optional.get();
            List<BusinessLedgerTask> databaseTaskList = businessLedgerTaskRepository.findAll(Example.of(BusinessLedgerTask.builder().ledgerId(id).build()));

            List<BusinessLedgerTask> taskList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(databaseTaskList)) {
                for (BusinessLedgerTask businessLedgerTask : databaseTaskList) {
                    BusinessLedgerTask task = new BusinessLedgerTask();
                    BeanUtils.copyProperties(businessLedgerTask, task);
                    if ("0".equals(task.getStatus()) && "2".equals(task.getWorkValueType())) {
                        task.setWorkValue(DateUtil.getNowDateString());
                    }
                    taskList.add(task);
                }
                ledger.setTaskList(taskList.stream().sorted(Comparator.comparing(BusinessLedgerTask::getTaskSort)
                        .thenComparing(BusinessLedgerTask::getId)).collect(Collectors.toList()));

            }
            return ledger;
        }
        return null;
    }

    /**
     * 查询简化台账信息-不包含任务信息
     *
     * @param id
     * @return
     */
    public BusinessLedger findSimpleLedgerById(Integer id) {
        Optional<BusinessLedger> optional = businessLedgerRepository.findById(id);
        if (optional.isPresent()) {
            BusinessLedger ledger = optional.get();
            return ledger;
        }
        return null;
    }


    /**
     * @param ledger
     */
    @Transactional
    public void createLedger(BusinessLedger ledger, User user) {
        Assert.isTrue(Objects.nonNull(ledger.getLedgerTemplateId()), "台账类型不可为空");
        LedgerTemplate template = findLedgerTemplateById(ledger.getLedgerTemplateId());

        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());
        BusinessLedger businessLedger = businessLedgerRepository.save(ledger);

        if (Objects.nonNull(template) && CollectionUtils.isNotEmpty(template.getTaskTemplateList())) {
            List<LedgerTaskTemplate> taskTemplateList = template.getTaskTemplateList();
            List<BusinessLedgerTask> taskList = Lists.newArrayList();
            for (LedgerTaskTemplate ledgerTaskTemplate : taskTemplateList) {
                BusinessLedgerTask businessLedgerTaskSaved = businessLedgerTaskRepository.save(BusinessLedgerTask.builder().createTime(LocalDateTime.now()).ledgerId(businessLedger.getId())
                        .status("0").workValueRequire(ledgerTaskTemplate.getWorkValueRequire()).workItem(ledgerTaskTemplate.getWorkItem())
                        .workValueType(ledgerTaskTemplate.getWorkValueType())
                        .taskSort(ledgerTaskTemplate.getTaskSort()).workType(ledgerTaskTemplate.getWorkType()).workItemType(ledgerTaskTemplate.getWorkItemType()).build());
                taskList.add(businessLedgerTaskSaved);
                //要查询这个模板任务是否关联了文件信息，如果关联了文件信息，则就生成台账文件列表
                List<LedgerTaskFileTemplate> fileTemplateList = listFileTemplateByType(ledgerTaskTemplate.getWorkItemType());
                if (CollectionUtils.isNotEmpty(fileTemplateList)) {
                    List<BusinessLedgerTaskFile> fileList = Lists.newArrayList();
                    for (LedgerTaskFileTemplate ledgerTaskFileTemplate : fileTemplateList) {
                        BusinessLedgerTaskFile file = new BusinessLedgerTaskFile();
                        BeanUtils.copyProperties(ledgerTaskFileTemplate, file);

                        file.setId(null);
                        file.setBusinessLedgerTaskId(businessLedgerTaskSaved.getId());
                        file.setCreateTime(LocalDateTime.now());
                        file.setFileTemplateId(ledgerTaskFileTemplate.getId());
                        file.setMemo(null);
                        file.setFileActualReceive(null);
                        fileList.add(file);
                    }

                    if (CollectionUtils.isNotEmpty(fileList)) {
                        businessLedgerTaskFileRepository.saveAll(fileList);
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(taskList)) {
                // 需要开启第一条任务待办提醒
                taskList = taskList.stream().sorted(Comparator.comparing(BusinessLedgerTask::getTaskSort)).collect(Collectors.toList());
                BusinessLedgerTask nowBusinessLedgerTask = taskList.get(0);
                String newTaskName = ledger.getName() + "-" + DateUtil.getNowDateString() + "-" + nowBusinessLedgerTask.getWorkItem();
                TaskInfo todoTask = TaskInfo.builder().createTime(new Date()).name(newTaskName).status("0")
                        .type(businessLedger.getToTaskType()).shotUrl(TaskTypeUrlEnum.LEDGER.getShotUrl() + businessLedger.getId())
                        .roleCode(TaskTypeUrlEnum.LEDGER.getRoleCode()).businessId(ledger.getId() + "").build();
                taskInfoService.saveTaskInfo(todoTask);

            }
        }
    }

    /**
     * 完成一条台账任务
     *
     * @param paramTask
     * @param user
     */
    @Transactional
    public void finishLedgerTask(BusinessLedgerTask paramTask, User user) {

        Optional<BusinessLedgerTask> taskOptional = businessLedgerTaskRepository.findById(paramTask.getId());
        BusinessLedgerTask task = taskOptional.get();

        if (("1".equals(task.getWorkValueType()) || "2".equals(task.getWorkValueType())) && StringUtils.isBlank(paramTask.getWorkValue())) {
            Assert.isTrue(false, "请填写工作值");
        }
        Assert.isTrue((StringUtils.isBlank(task.getStatus()) || task.getStatus().equals("0")), "任务已完成");

        //有文件清单需要校验
        if (StringUtils.isNotBlank(task.getWorkItemType()) && !"no_opt".equals(task.getWorkItemType())) {
            List<BusinessLedgerTaskFile> files = businessLedgerTaskFileRepository.findAll(Example.of(BusinessLedgerTaskFile.builder().businessLedgerTaskId(task.getId()).build()));
            if (CollectionUtils.isNotEmpty(files)) {
                files = files.stream().filter(e -> "Y".equals(e.getFileRequire()) && (StringUtils.isBlank(e.getFileActualReceive()) || "N".equals(e.getFileActualReceive()))).collect(Collectors.toList());
                Assert.isTrue(CollectionUtils.isEmpty(files), "请先完成材料清单中的必填文件的签收");
            }
        }


        task.setFinishId(user.getId());
        task.setFinishTime(LocalDateTime.now());
        task.setMemo(paramTask.getMemo());
        task.setFinishUserName(user.getName());
        task.setWorkValue(paramTask.getWorkValue());
        task.setStatus("1");

        BusinessLedger ledger = findLedgerById(task.getLedgerId());

        //1.结束当前台账任务
        businessLedgerTaskRepository.save(task);

        TaskInfo todoTask = taskInfoService.findByBusinessIdAndType(task.getLedgerId() + "", ledger.getToTaskType());

        //校验工作值是否必填和任务完成顺序是否正确
        ledgerTaskCheck(task, ledger);

        if ("1".equals(ledger.getStatus())) {
            return;
        }

        List<BusinessLedgerTask> taskList = ledger.getTaskList();
        if (CollectionUtils.isEmpty(taskList)) {
            finishTaskInfoItem(ledger, todoTask, user);
            return;
        }

        taskList = taskList.stream().filter(e -> (e.getId() != task.getId() && "Y".equals(e.getWorkValueRequire()) && "0".equals(e.getStatus()))).collect(Collectors.toList());

        //3.检查所有待办是否都已经完成,如果都已经完成,则将台账状态修改为完成
        if (CollectionUtils.isEmpty(taskList)) {
            finishTaskInfoItem(ledger, todoTask, user);
            return;
        }

        taskList = taskList.stream().filter(e -> e.getStatus().equals("0")).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(taskList)) {
            finishTaskInfoItem(ledger, todoTask, user);
            return;
        }

        //4.如果有台账任务未完成,则寻找下一条待办的台账任务，并修改待办任务名称为新的台账任务名称
        taskList = taskList.stream().sorted(Comparator.comparing(BusinessLedgerTask::getTaskSort)).collect(Collectors.toList());
        BusinessLedgerTask nowBusinessLedgerTask = taskList.get(0);
        String newTaskName = ledger.getName() + "-" + DateUtil.getNowDateString() + "-" + nowBusinessLedgerTask.getWorkItem();

        if (Objects.nonNull(todoTask)) {
            todoTask.setName(newTaskName);
        } else {
            todoTask = TaskInfo.builder().createTime(new Date()).name(newTaskName).status("0")
                    .type(ledger.getToTaskType()).shotUrl(TaskTypeUrlEnum.LEDGER.getShotUrl() + ledger.getId())
                    .roleCode(TaskTypeUrlEnum.LEDGER.getRoleCode()).businessId(ledger.getId() + "").build();
        }
        taskInfoService.saveTaskInfo(todoTask);
        //saveBusinessLedger(ledger);
    }

    /**
     * 校验任务前置条件是否完成
     */
    public void ledgerTaskCheck(BusinessLedgerTask task, BusinessLedger ledger) {
        if (("1".equals(task.getWorkValueType()) || "2".equals(task.getWorkValueType())) && StringUtils.isBlank(task.getWorkValue())) {
            Assert.isTrue(false, "请填写工作值");
        }
        List<BusinessLedgerTask> taskList = ledger.getTaskList();
        taskList = taskList.stream().filter(e -> e.getId() != task.getId()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(taskList)) {
            return;
        }

        taskList = taskList.stream().filter(e -> "Y".equals(e.getWorkValueRequire()) && e.getStatus().equals("0") && e.getTaskSort() < task.getTaskSort()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(taskList)) {
            return;
        }

        //4.如果有台账任务未完成,则寻找下一条待办的台账任务，并修改待办任务名称为新的台账任务名称
        taskList = taskList.stream().sorted(Comparator.comparing(BusinessLedgerTask::getTaskSort)).collect(Collectors.toList());
        BusinessLedgerTask nowBusinessLedgerTask = taskList.get(0);
        if (nowBusinessLedgerTask.getTaskSort() < task.getTaskSort()) {
            Assert.isTrue(nowBusinessLedgerTask.getTaskSort() >= task.getTaskSort(), "请先去完成[" + nowBusinessLedgerTask.getWorkItem() + "]任务");
        }

    }

    private void finishTaskInfoItem(BusinessLedger ledger, TaskInfo todoTask, User user) {
        if (Objects.nonNull(ledger)) {
            ledger.setFinishId(user.getId());
            ledger.setFinishUserName(user.getName());
            ledger.setStatus("1");
            ledger.setFinishTime(DateUtil.getNowDateString());
            saveBusinessLedger(ledger);
        }

        if (Objects.nonNull(todoTask)) {
            todoTask.setFinishTime(new Date());
            todoTask.setStatus("1");
            taskInfoService.saveTaskInfo(todoTask);
        }
    }


    /**
     * 保存台账信息-只能修改台账名称和台账备注
     *
     * @param businessLedger
     */
    public void saveBusinessLedger(BusinessLedger businessLedger) {

        Optional<BusinessLedger> optional = businessLedgerRepository.findById(businessLedger.getId());
        if (optional.isPresent()) {
            BusinessLedger oldLedger = optional.get();
            oldLedger.setName(businessLedger.getName());
            oldLedger.setMemo(businessLedger.getMemo());
            businessLedgerRepository.save(oldLedger);
        }
    }

    /**
     * 保存台账任务信息
     *
     * @param task
     */
    public void saveBusinessLedgerTask(BusinessLedgerTask task) {
        businessLedgerTaskRepository.save(task);
    }


    /**
     * 分页查询台账任务文件模板
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<LedgerTaskFileTemplate> findLedgerTaskFileTemplatePage(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<LedgerTaskFileTemplate> page = ledgerTaskFileTemplateRepository.findAll(SpecificationUtil.buildSpecification(param, LedgerTaskFileTemplate.class), pageable);

        return page;
    }

    /**
     * 保存台账任务文件模板
     *
     * @param ledgerTaskFileTemplate
     */
    public void saveLedgerTaskFileTemplate(LedgerTaskFileTemplate ledgerTaskFileTemplate) {
        ledgerTaskFileTemplateRepository.save(ledgerTaskFileTemplate);
    }

    /**
     * 删除台账任务文件模板
     *
     * @param id
     */
    public void deleteLedgerTaskFileTemplate(Integer id) {
        ledgerTaskFileTemplateRepository.deleteById(id);
    }

    /**
     * 根据类型获取台账任务文件模板列表
     *
     * @param type
     * @return
     */
    public List<LedgerTaskFileTemplate> listFileTemplateByType(String type) {
        if (StringUtils.isBlank(type)) {
            return null;
        }
        return ledgerTaskFileTemplateRepository.findAll(Example.of(LedgerTaskFileTemplate.builder().workItemType(type).build()));
    }

    @Transactional
    public void updateFile(Integer id, String workValue, String memo, User user) {
        Optional<BusinessLedgerTaskFile> optional = businessLedgerTaskFileRepository.findById(id);
        if (!optional.isPresent()) {
            return;
        }
        BusinessLedgerTaskFile file = optional.get();
        file.setMemo(memo);
        file.setWorkValue(workValue);
        file.setFinishId(user.getId());
        file.setFinishTime(LocalDateTime.now());
        file.setFinishUserName(user.getName());
        businessLedgerTaskFileRepository.save(file);
    }


    /**
     * 根据id签收一条台账任务文件
     *
     * @param id
     */
    @Transactional
    public void finishFile(Integer id, String workValue, String memo, User user) {

        Optional<BusinessLedgerTaskFile> optional = businessLedgerTaskFileRepository.findById(id);
        if (!optional.isPresent()) {
            return;
        }
        BusinessLedgerTaskFile file = optional.get();

        Assert.isTrue((StringUtils.isBlank(file.getFileActualReceive()) || file.getFileActualReceive().equals("N")), "文件已签收");
        if (StringUtils.isNotBlank(file.getWorkValueType()) && "2".equals(file.getWorkValueType()) && StringUtils.isBlank(workValue)) {
            Assert.isTrue(false, "请填写工作值");
        }

        file.setFileActualReceive("Y");
        file.setMemo(memo);
        file.setWorkValue(workValue);
        file.setFinishId(user.getId());
        file.setFinishTime(LocalDateTime.now());
        file.setFinishUserName(user.getName());
        businessLedgerTaskFileRepository.save(file);


        BusinessLedgerTask task = findTaskById(file.getBusinessLedgerTaskId());

        //查询所有必须签收的文件，如果必须签收的文件都已经签收则结束该条任务
        List<BusinessLedgerTaskFile> fileList = businessLedgerTaskFileRepository.findAll(Example.of(BusinessLedgerTaskFile.builder()
                .businessLedgerTaskId(task.getId()).build()));
        if (CollectionUtils.isEmpty(fileList) && task.getStatus().equals("0")) {
            try {
                finishLedgerTask(task, user);
            } catch (Exception e) {
                log.error("从台账文件自动结束台账任务失败", e);
            }
        }
        List<BusinessLedgerTaskFile> noFinishFileList = fileList.stream().filter(e -> "Y".equals(e.getFileRequire()) &&
                (StringUtils.isBlank(e.getFileActualReceive()) || "N".equals(e.getFileActualReceive()))).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(noFinishFileList) && task.getStatus().equals("0")) {
            try {
                finishLedgerTask(task, user);
            } catch (Exception e) {
                log.error("从台账文件自动结束台账任务失败", e);
            }
        }

    }

    /**
     * 根据任务id查询所有关联的文件信息
     *
     * @param taskId
     * @return
     */
    public List<BusinessLedgerTaskFile> listTaskFileByTaskId(Integer taskId) {
        return businessLedgerTaskFileRepository.findAll(Example.of(BusinessLedgerTaskFile.builder().businessLedgerTaskId(taskId).build()));
    }

    /**
     * 根据id获取任务信息，如果附件信息存在则获取附件信息
     *
     * @param id
     * @return
     */
    public BusinessLedgerTask findTaskById(Integer id) {
        Optional<BusinessLedgerTask> optional = businessLedgerTaskRepository.findById(id);
        if (optional.isPresent()) {
            BusinessLedgerTask task = optional.get();
            List<BusinessLedgerTaskFile> files = businessLedgerTaskFileRepository.findAll(Example.of(BusinessLedgerTaskFile.builder().businessLedgerTaskId(task.getId()).build()));
            task.setFileList(files);
            return task;
        }
        return null;
    }


    /**
     * 更新台账任务的工作值，并记录操作日志
     *
     * @param task
     */
    public void updateWorkValue(BusinessLedgerTask task, User user) {
        if (Objects.isNull(task) || Objects.isNull(task.getId())) {
            return;
        }
        Optional<BusinessLedgerTask> optional = businessLedgerTaskRepository.findById(task.getId());
        if (!optional.isPresent()) {
            return;
        }
        BusinessLedgerTask businessLedgerTask = optional.get();

        BusinessLedgerOptLog optLog = BusinessLedgerOptLog.builder().createId(user.getId()).createName(user.getName())
                .createTime(LocalDateTime.now()).ledgerId(businessLedgerTask.getLedgerId())
                .ledgerTaskId(businessLedgerTask.getId()).newLedgerData(businessLedgerTask.getWorkValue()).oldLedgerData(task.getWorkValue()).optType("1").build();

        businessLedgerTask.setWorkValue(task.getWorkValue());
        businessLedgerTask.setMemo(task.getMemo());
        businessLedgerTaskRepository.save(businessLedgerTask);
        //记录操作日志

        businessLedgerOptLogRepository.save(optLog);
    }


    /**
     * 每天八点自动创建交易台账
     */
    @XxlJob("ledgerService_autoCreateJyLedger")
    public void autoCreateJyLedger() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        BusinessLedger ledger = new BusinessLedger();
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("jiaoyi_yewu").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "交易台账");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动创建基金投顾业务台账
     */
    @XxlJob("ledgerService_autoCreateJyLedgerJiJin")
    public void autoCreateJyLedgerJiJin() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 基金投顾业务
        List<LedgerTemplate> templateListJiJin = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("jijin_tougu").build()));
        if (CollectionUtils.isEmpty(templateListJiJin)) {
            return;
        }
        BusinessLedger ledgerJiJin = new BusinessLedger();
        DateFormat dateFormatJiJin = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate templateJiJin = templateListJiJin.get(0);
        ledgerJiJin.setName(dateFormatJiJin.format(new Date()) + "基金投顾业务");
        ledgerJiJin.setLedgerTemplateId(templateJiJin.getId());
        ledgerJiJin.setStatus("0");
        ledgerJiJin.setCreateId(user.getId());
        ledgerJiJin.setCreateName(user.getName());
        ledgerJiJin.setTemplateName(templateJiJin.getName());
        ledgerJiJin.setToTaskType(templateJiJin.getToTaskType());

        createLedger(ledgerJiJin, user);

    }

    /**
     * 每天八点自动创建大宗交易业务台账
     */
    @XxlJob("ledgerService_autoCreateJyLedgerDaZong")
    public void autoCreateJyLedgerDaZong() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateListDaZong = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("dazong_jiaoyi").build()));
        if (CollectionUtils.isEmpty(templateListDaZong)) {
            return;
        }
        BusinessLedger ledgerDaZong = new BusinessLedger();
        DateFormat dateFormatDaZong = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate templateDaZong = templateListDaZong.get(0);
        ledgerDaZong.setName(dateFormatDaZong.format(new Date()) + "大宗交易");
        ledgerDaZong.setLedgerTemplateId(templateDaZong.getId());
        ledgerDaZong.setStatus("0");
        ledgerDaZong.setCreateId(user.getId());
        ledgerDaZong.setCreateName(user.getName());
        ledgerDaZong.setTemplateName(templateDaZong.getName());
        ledgerDaZong.setToTaskType(templateDaZong.getToTaskType());

        createLedger(ledgerDaZong, user);

    }


    /**
     * 每天八点自动固收运营资金
     */
    @XxlJob("ledgerService_autoCreateJyLedgerZiJin")
    public void autoCreateJyLedgerZiJin() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateListZiJin = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("gushou_yunying_zj").build()));
        if (CollectionUtils.isEmpty(templateListZiJin)) {
            return;
        }
        BusinessLedger ledgerZiJin = new BusinessLedger();
        DateFormat dateFormatZiJin = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate templateZiJin = templateListZiJin.get(0);
        ledgerZiJin.setName(dateFormatZiJin.format(new Date()) + "固收资金类");
        ledgerZiJin.setLedgerTemplateId(templateZiJin.getId());
        ledgerZiJin.setStatus("0");
        ledgerZiJin.setCreateId(user.getId());
        ledgerZiJin.setCreateName(user.getName());
        ledgerZiJin.setTemplateName(templateZiJin.getName());
        ledgerZiJin.setToTaskType(templateZiJin.getToTaskType());

        createLedger(ledgerZiJin, user);

    }

    /**
     * 每天八点自动固收运营报表
     */
    @XxlJob("ledgerService_autoCreateJyLedgerBaoBiao")
    public void autoCreateJyLedgerBaoBiao() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateListBaoBiao = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("gushou_yunying_bb").build()));
        if (CollectionUtils.isEmpty(templateListBaoBiao)) {
            return;
        }
        BusinessLedger ledgerBaoBiao = new BusinessLedger();
        DateFormat dateFormatBaoBiao = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate templateBaoBiao = templateListBaoBiao.get(0);
        ledgerBaoBiao.setName(dateFormatBaoBiao.format(new Date()) + "固收报表类");
        ledgerBaoBiao.setLedgerTemplateId(templateBaoBiao.getId());
        ledgerBaoBiao.setStatus("0");
        ledgerBaoBiao.setCreateId(user.getId());
        ledgerBaoBiao.setCreateName(user.getName());
        ledgerBaoBiao.setTemplateName(templateBaoBiao.getName());
        ledgerBaoBiao.setToTaskType(templateBaoBiao.getToTaskType());

        createLedger(ledgerBaoBiao, user);

    }

    /**
     * 每天八点自动固收运营结算
     */
    @XxlJob("ledgerService_autoCreateJyLedgerJieSuan")
    public void autoCreateJyLedgerJieSuan() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateListJieSuan = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("gushou_yunying_js").build()));
        if (CollectionUtils.isEmpty(templateListJieSuan)) {
            return;
        }
        BusinessLedger ledgerJieSuan = new BusinessLedger();
        DateFormat dateFormatJieSuan = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate templateJieSuan = templateListJieSuan.get(0);
        ledgerJieSuan.setName(dateFormatJieSuan.format(new Date()) + "固收结算类");
        ledgerJieSuan.setLedgerTemplateId(templateJieSuan.getId());
        ledgerJieSuan.setStatus("0");
        ledgerJieSuan.setCreateId(user.getId());
        ledgerJieSuan.setCreateName(user.getName());
        ledgerJieSuan.setTemplateName(templateJieSuan.getName());
        ledgerJieSuan.setToTaskType(templateJieSuan.getToTaskType());

        createLedger(ledgerJieSuan, user);

    }

    /**
     * 每天八点自动期权全真环境
     */
    @XxlJob("ledgerService_autoCreateJyLedgerQz")
    public void autoCreateJyLedgerQz() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateListQz = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_uf20_qz").build()));
        if (CollectionUtils.isEmpty(templateListQz)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateListQz.get(0);
        ledger.setName(dateFormat.format(new Date()) + "期权全真环境");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动衡泰系统
     */
    @XxlJob("ledgerService_autoCreateJyLedgerHt")
    public void autoCreateJyLedgerHt() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_htxt").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "衡泰系统");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动凌瓴系统
     */
    @XxlJob("ledgerService_autoCreateJyLedgerLl")
    public void autoCreateJyLedgerLl() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_llxt").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "凌瓴系统");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动i2系统
     */
    @XxlJob("ledgerService_autoCreateJyLedgerI2")
    public void autoCreateJyLedgerI2() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_i2xt").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "i2系统");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }


    /**
     * 每天八点自动PB系统
     */
    @XxlJob("ledgerService_autoCreateJyLedgerPb")
    public void autoCreateJyLedgerPb() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_pbxt").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "PB系统");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动O32系统
     */
    @XxlJob("ledgerService_autoCreateJyLedgerO32")
    public void autoCreateJyLedgerO32() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_o32").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "O32系统");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }


    /**
     * 每天八点自动法人系统
     */
    @XxlJob("ledgerService_autoCreateJyLedgerFr")
    public void autoCreateJyLedgerFr() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_frxt").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "法人系统");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动基金投顾
     */
    @XxlJob("ledgerService_autoCreateJyLedgerJt")
    public void autoCreateJyLedgerJt() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_jjtgxt").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "基金投顾");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动数据清分辅助平台
     */
    @XxlJob("ledgerService_autoCreateJyLedgerSj")
    public void autoCreateJyLedgerSj() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_sjqffzxt").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "数据清分辅助平台");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动内存清算系统
     */
    @XxlJob("ledgerService_autoCreateJyLedgerNc")
    public void autoCreateJyLedgerNc() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_ncqsxt").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "内存清算系统");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /**
     * 每天八点自动机构柜台
     */
    @XxlJob("ledgerService_autoCreateJyLedgerGt")
    public void autoCreateJyLedgerGt() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_uf20_jg").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "机构柜台");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }


    /**
     * 每天八点自动零售柜台
     */
    @XxlJob("ledgerService_autoCreateJyLedgerLs")
    public void autoCreateJyLedgerLs() {
        //查询今天是否涉及交易日
        User user = new User();
        user.setId(1L);
        user.setName("系统创建");
        Boolean isTradeDay = tradingDayService.getToday(DateUtils.getCurrentDate(formatDate));
        if (!isTradeDay) {
            return;
        }
        // 大宗交易业务
        List<LedgerTemplate> templateList = ledgerTemplateRepository.findAll(Example.of(LedgerTemplate.builder().toTaskType("qs_uf20_ls").build()));
        if (CollectionUtils.isEmpty(templateList)) {
            return;
        }
        BusinessLedger ledger = new BusinessLedger();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        LedgerTemplate template = templateList.get(0);
        ledger.setName(dateFormat.format(new Date()) + "零售柜台");
        ledger.setLedgerTemplateId(template.getId());
        ledger.setStatus("0");
        ledger.setCreateId(user.getId());
        ledger.setCreateName(user.getName());
        ledger.setTemplateName(template.getName());
        ledger.setToTaskType(template.getToTaskType());

        createLedger(ledger, user);

    }

    /*public Boolean getToday(String currentDate) {
        ResponseEntity<PlatformResponse> forEntity = restTemplate.getForEntity("http://" + glbaseDataUrl + "/glbasedata/commonquery/getData?" +
                "infName=checkTradeDay&sysName=OPManagerSystem&pwd=glbase2opsys" +
                "&param1=" + currentDate + "&param2=SSE", PlatformResponse.class);
        if (forEntity == null || forEntity.getBody() == null || forEntity.getBody().getData() == null) {
            throw PlatformException.error("ledgerService_autoCreateJyLedger error 调用接口出错:" + forEntity);
        }
        Map data = (Map) forEntity.getBody().getData();
        List<List> context = (ArrayList<List>) data.get("context");
        if (CollectionUtils.isEmpty(context)) {
            throw PlatformException.error("ledgerService_autoCreateJyLedger error 调用接口出错:" + forEntity);
        }
        List<Boolean> contextInner = context.get(0);
        return contextInner.get(0);
    }*/

    /**
     * 每周发送收到的kyc sac相关附件
     */
    @XxlJob("ledgerService_sendKycSacFileListEmail")
    public void sendKycSacFileListEmail() {
        //邮件附件列表
        List<File> attachmentList = Lists.newArrayList();

        //查询最近一周的文件信息
        Map<String, Object> param = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        param.put("GTE_finishTime", dateFormat.format(calendar.getTime()));
        param.put("LGTE_finishTime", dateFormat.format(new Date()));
        List<BusinessLedgerTaskFile> fileList = businessLedgerTaskFileRepository.findAll(SpecificationUtil.buildSpecification(param, BusinessLedgerTaskFile.class));

        if (CollectionUtils.isEmpty(fileList)) {
            return;
        }

        List<BusinessLedgerFileExcelDto> orgExcelFileList = Lists.newArrayList();
        List<BusinessLedgerFileExcelDto> prodExcelFileList = Lists.newArrayList();

        //机构文件列表
        List<BusinessLedgerTaskFile> orgFileList = fileList.stream().filter(e -> "kyc_sac_org".equals(e.getWorkItemType())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(orgFileList)) {
            Map<Integer, List<BusinessLedgerTaskFile>> taskIdFileListMap = orgFileList.stream().filter(e -> "Y".equals(e.getFileActualReceive()))
                    .collect(Collectors.groupingBy(BusinessLedgerTaskFile::getBusinessLedgerTaskId, Collectors.mapping(e -> e, Collectors.toList())));
            for (Integer taskId : taskIdFileListMap.keySet()) {
                BusinessLedgerTask task = findTaskById(taskId);
                BusinessLedger ledger = findLedgerById(task.getLedgerId());
                List<BusinessLedgerTaskFile> files = taskIdFileListMap.get(taskId).stream().sorted(Comparator.comparing(BusinessLedgerTaskFile::getFileSort)).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(files)) {
                    for (BusinessLedgerTaskFile file : files) {
                        orgExcelFileList.add(BusinessLedgerFileExcelDto.builder().name(ledger.getName()).fileName(file.getFileName()).memo("实际收到").build());
                    }
                }
            }
            try {
                byte[] export = ReportFileUtil.export(orgExcelFileList, ReportFileConfigEnum.KYC_SAC_LEDGER_FILE_EXPORT);
                MultipartFile multipartFile = new MockMultipartFile("机构文档清单.xlsx", "机构文档清单.xlsx", ContentType.APPLICATION_OCTET_STREAM.toString(), export);
                File file = new File("机构文档清单" + dateFormat.format(new Date()) + ".xlsx");
                FileCopyUtils.copy(multipartFile.getBytes(), file);
                attachmentList.add(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //产品文件列表
        List<BusinessLedgerTaskFile> prodFileList = fileList.stream().filter(e -> "kyc_sac_prod".equals(e.getWorkItemType())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(prodFileList)) {
            Map<Integer, List<BusinessLedgerTaskFile>> taskIdFileListMap = orgFileList.stream().filter(e -> "Y".equals(e.getFileActualReceive()))
                    .collect(Collectors.groupingBy(BusinessLedgerTaskFile::getBusinessLedgerTaskId, Collectors.mapping(e -> e, Collectors.toList())));
            for (Integer taskId : taskIdFileListMap.keySet()) {
                BusinessLedgerTask task = findTaskById(taskId);
                BusinessLedger ledger = findLedgerById(task.getLedgerId());
                List<BusinessLedgerTaskFile> files = taskIdFileListMap.get(taskId).stream().sorted(Comparator.comparing(BusinessLedgerTaskFile::getFileSort)).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(files)) {
                    for (BusinessLedgerTaskFile file : files) {
                        prodExcelFileList.add(BusinessLedgerFileExcelDto.builder().name(ledger.getName()).fileName(file.getFileName()).memo("实际收到").build());
                    }
                }
            }

            try {
                byte[] export = ReportFileUtil.export(prodExcelFileList, ReportFileConfigEnum.KYC_SAC_LEDGER_FILE_EXPORT);
                MultipartFile multipartFile = new MockMultipartFile("产品文档清单.xlsx", "产品文档清单.xlsx", ContentType.APPLICATION_OCTET_STREAM.toString(), export);
                File file = new File("产品文档清单" + dateFormat.format(new Date()) + ".xlsx");
                FileCopyUtils.copy(multipartFile.getBytes(), file);
                attachmentList.add(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (CollectionUtils.isNotEmpty(attachmentList)) {
            String title = "交易单元收费明细";
            String content = "本周收到的KYC、SAC文档清单请详见附件。如需增加，请提供相关文件并联系运营管理总部股衍运营岗。";

            //收件人邮箱
            List<String> recvMailList = Lists.newArrayList();
            //recvMailList.add("gy_mo@glsc.com.cn");
            recvMailList.add("weili@glsc.com.cn");
            String emailId = mailService.sendMail(recvMailList, null, title, content, attachmentList);
        }

    }


}
